package com.ms.service.module.fish.test;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

import com.xpec.c4.codec.CodecUtility;
import com.xpec.c4.net.XSEPacketCategoryMeter;
import com.xpec.c4.service.message.NetMessage;

public class XSENetNettyEncoder extends OneToOneEncoder
{
	private static final short START_FLAG = Short.MAX_VALUE;

	@Override
	protected Object encode(ChannelHandlerContext ctx, Channel channel, Object obj) throws Exception
	{
		if( !channel.isConnected() )
			return obj;
		
		/// 跟 NetMessage 非相關的東西就不 encode
		if( !(obj instanceof NetMessage) )
		{
			return obj;
		}
		
		NetMessage message = (NetMessage)obj;
		
		int messageType = message.getMessageType();
		byte[] bb = message.getMessageContentBytes();
		if( bb == null )
		{
			bb = CodecUtility.contentEncode(message.getMessageContent(),messageType);
		}
		
		byte[] mdid = CodecUtility.h2oEncode(message.getModuleID());
		ChannelBuffer header = ChannelBuffers.buffer(2+4+mdid.length+4);
		header.writeShort(START_FLAG);
		header.writeInt(bb.length+mdid.length + 4);
		header.writeBytes(mdid);
		header.writeInt(messageType);

		ChannelBuffer body = ChannelBuffers.wrappedBuffer(bb);
		
		XSEPacketCategoryMeter.getInstance().recordOutput(messageType, bb.length+10);
		
		return ChannelBuffers.wrappedBuffer(header,body);
	}

}